<?php

class Ctrl {
	/**
	 * 
	 * @var PDIO
	 */
	public $pdio;
	/**
	 * 
	 * @var Request
	 */
	protected $request;
	/**
	 * 
	 * @var Response
	 */
	public $response;
	/**
	 * 
	 * @var TimeMachine
	 */
	public $delorean;
	
	public $plugins;
	
	
	
	public function __construct($req, $timeMach, $pdio) {
		
		$this->request	= $req;
		$this->delorean = $timeMach;
		$this->response = new Response();
		$this->pdio = $pdio;

	}
	
	public function getResponse() {
		return $this->response;
	}
	
	public function getError(&$msg, $writeToResp) {
		
		$error = false;
		$msg = '';
		
		if ($this->request->get('showError') === true) {
			$error = $this->request->get('showError');
			$msg = $this->request->get('errorMsg');
			
			$this->delorean->cleanError();
			
			if ($writeToResp) {
				$this->response->set('showError', $error);
				$this->response->set('errorMsg', $msg);
			}
			
		}
		
		return $error;
		
	}
	
	
	private function beforeAction() {
	}
	
	private function afterAction() {}
	
	public function invokeAction($act){
		try {
		    $this->beforeAction();
		    $this->$act();
		    $this->afterAction();
		} catch (SendBackException $sbe) {
			$this->goBack($sbe->getMessage());
		} catch (goBackException $gbe) {
		    throw $gbe;
		} catch (reloadBackException $rbe) {
		     throw $rbe;
		}
	    
	}
	
	public function goBack($errorMsg = '') {
		if ($errorMsg != '') {
			$this->response->set('errorMsg', $errorMsg);
			$this->response->set('showError', true);
		}
		$this->delorean->goBack($this->response->getParams());
	}
	
	public function reloadBack($errorMsg = '') {
	    if ($errorMsg != '') {
	        $this->response->set('errorMsg', $errorMsg);
	        $this->response->set('showError', true);
	    }
	    $this->delorean->reloadBack($this->response->getParams());
	}	
	
	public function reloadRefresh($errorMsg = '') {
	    
	    if ($errorMsg != '') {
	        $this->response->set('errorMsg', $errorMsg);
	        $this->response->set('showError', true);
	    }
	    $this->delorean->reloadRefresh($this->response->getParams());
	}	
	
	public function goRefresh($errorMsg = '') {
	     
	    if ($errorMsg != '') {
	        $this->response->set('errorMsg', $errorMsg);
	        $this->response->set('showError', true);
	    }
	    $this->delorean->goRefresh($this->response->getParams());
	}	
	
	
}



?>
